import { Directive, DirectiveBinding } from "vue";

interface GradientTextOptions {
  colors?: string[];
  size?: string;
  duration?: number;
}

export const vColorText: Directive<
  HTMLElement,
  GradientTextOptions | undefined
> = {
  mounted(
    el: HTMLElement,
    binding: DirectiveBinding<GradientTextOptions | undefined>
  ) {
    const defaultOptions: GradientTextOptions = {
      colors: ["#4facfe", "#00f2fe", "white", "#00f2fe", "#4facfe"],
      size: "300% 100%",
      duration: 5,
    };

    const options = binding.value
      ? { ...defaultOptions, ...binding.value }
      : defaultOptions;

    // 应用样式
    // el.style.fontSize = "48px";
    el.style.fontWeight = "bold";
    el.style.background = `linear-gradient(90deg, ${options.colors?.join(
      ", "
    )})`;
    el.style.backgroundSize = options.size ?? defaultOptions.size;
    el.style.webkitBackgroundClip = "text";
    el.style.backgroundClip = "text";
    el.style.color = "transparent";
    el.style.display = "inline-block";

    // 创建动画
    const animationName = `gradientMove-${Math.random()
      .toString(36)
      .substring(2, 9)}`;
    const styleTag = document.createElement("style");
    styleTag.textContent = `
      @keyframes ${animationName} {
        0% { background-position: 0% 50%; }
        100% { background-position: 100% 50%; }
      }
    `;
    document.head.appendChild(styleTag);

    el.style.animation = `${animationName} ${options.duration}s linear infinite`;

    // 保存引用以便卸载时清理
    el._gradientTextStyleTag = styleTag;
  },
  unmounted(el: HTMLElement) {
    // 清理样式标签
    if (el._gradientTextStyleTag) {
      document.head.removeChild(el._gradientTextStyleTag);
    }
  },
};
